package com.hangzhou.xyj.utils;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;

import com.hangzhou.xyj.R;
import com.hangzhou.xyj.XYJApplication;
import com.hangzhou.xyj.model.type.EFileType;
import com.hangzhou.xyj.model.type.EUserType;
import com.hangzhou.xyj.ui.widget.views.MyTextView;
import com.mediaideas.videoengine.constants.AppConstants;
import com.mediaideas.videoengine.utils.FileUtils;
import com.mediaideas.videoengine.utils.XYJException;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.lang.reflect.Field;

import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.onekeyshare.OnekeyShare;

/**
 * 公共工具类
 *
 * @author neo.duan
 */
public class PublicUtil {
    private final static String TAG = "PublicUtil";
    //用于匹配手机号码
    private final static String REGEX_MOBILEPHONE = "^0?1[3458]\\d{9}$";
    //用于匹配固定电话号码
    private final static String REGEX_TELPHONE = "^(010|02\\d|0[3-9]\\d{2})?\\d{6,8}$";
    //匹配邮政编码
    private final static String REGEX_POSTCODE = "[1-9]\\d{5}(?!\\d)";
    //匹配邮箱
    private final static String REGEX_EMAIL = "\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";

    /**
     * 获取屏幕宽
     *
     * @return
     */
    public static int getScreenWidth() {
        return getScreenPoint().x;
    }

    /**
     * 获取屏幕高
     *
     * @return
     */
    public static int getScreenHeight() {
        return getScreenPoint().y;
    }

    @SuppressLint("NewApi")
    public static Point getScreenPoint() {
        WindowManager wm = (WindowManager) XYJApplication.mAppContext.getSystemService(Context.WINDOW_SERVICE);
        Point point = new Point();
        Display display = wm.getDefaultDisplay();
        display.getSize(point);
        return point;
    }

    /**
     * 获取图片名称获取图片的资源id的方法
     *
     * @param imageName
     * @return
     */
    public static int getResource(String imageName) {
        Class drawable = R.drawable.class;
        Field field = null;
        int r_id;
        try {
            field = drawable.getField(imageName);
            r_id = field.getInt(field.getName());
        } catch (Exception e) {
//	    	   r_id=R.drawable.ic_launcher;  
            r_id = -1;
            Log.e("ERROR", "PICTURE NOT　FOUND！");
        }
        return r_id;
    }

    /**
     * 根据resId获取文件名
     *
     * @param context
     * @param resId
     * @return
     */
    public static String getFileName(Context context, int resId) {
        String iconName = context.getResources().getResourceName(resId);
        int index = iconName.lastIndexOf("/");
        return iconName.substring(index + 1, iconName.length());
    }

    /**
     * 验证手机电话
     *
     * @param phone
     * @return
     */
    public static boolean isMobilePhone(String phone) {
        return phone.trim().matches(REGEX_MOBILEPHONE);
    }

    /**
     * 验证固定电话
     *
     * @param phone
     * @return
     */
    public static boolean isTelPhone(String phone) {
        return phone.trim().matches(REGEX_TELPHONE);
    }

    /**
     * 验证邮政编码
     */
    public static boolean isPostalCode(String post) {
        return post.trim().matches(REGEX_POSTCODE);
    }

    /**
     * Converts seconds to string, format mm:ss e.g. 04:12
     * 秒转成String
     *
     * @param seconds
     * @return
     */
    public static String secondsToString(int seconds) {
        String s = "" + seconds / 60 + ":";
        int t = seconds % 60;
        s += t < 10 ? "0" + t : t;
        return s;
    }

    /**
     * @param type      用户类型：1 是普通用户 2 是名家 3 是名团
     * @param checkFlag //0 待审核 1 个人认证 2 团体认证 4 审核未通过
     * @return
     * @Description 获取用户的具体类型
     * @author yaohuix
     * @date 2016/3/4 15:25
     */
    public static EUserType getUserType(int type, int checkFlag) {
        if (type == 1 && checkFlag == 1) return EUserType.AUTHORIZED_USER;
        else if (type == 1 && checkFlag == 2) return EUserType.AUTHORIZED_TEAM;
        else if (type == 2) return EUserType.FAMOUS_EXPERT;
        else if (type == 3) return EUserType.FAMOUS_TEAM;
        else if (type == 1) return EUserType.NORMAL_USER;
        else return EUserType.UNKNOWN;
    }

    /**
     * 获取用户类型的Str
     *
     * @param
     * @return
     * @author yaohuix
     * @date 2016/3/16 13:48
     */
    public static String getUserTypeStr(int type, int checkFlag) {
        if (type == 1 && checkFlag == 1) return "认证用户";
        else if (type == 1 && checkFlag == 2) return "认证团体";
        else if (type == 2) return "名家";
        else if (type == 3) return "名团";
        else if (type == 1) return "普通用户";
        else return "未知用户";
    }

    /**
     * 获取认证图片的Drawable对象
     *
     * @param
     * @return
     * @author yaohuix
     * @date 2016/3/2 19:42
     */
    public static Drawable getAuthenIconDrawable(Context context, EUserType userType) {
        Drawable drawableRight;
        switch (userType) {
            case AUTHORIZED_TEAM:
                drawableRight = context.getResources().getDrawable(R.drawable.ic_authen_team);
                break;
            case AUTHORIZED_USER:
                drawableRight = context.getResources().getDrawable(R.drawable.ic_authen_user);
                break;
            case FAMOUS_TEAM:
                drawableRight = context.getResources().getDrawable(R.drawable.ic_authen_famous_team);
                break;
            case FAMOUS_EXPERT:
                drawableRight = context.getResources().getDrawable(R.drawable.ic_authen_famous_expert);
                break;
            case NORMAL_USER:
                drawableRight = context.getResources().getDrawable(R.drawable.ic_authen_normal);
                break;
            default:
                drawableRight = null;
                break;
        }
        return drawableRight;
    }

    public static String getAuthenIconStringUri(Context context, EUserType userType) {
        switch (userType) {
            case AUTHORIZED_TEAM:
                return "drawable://" + R.drawable.ic_authen_team;
            case AUTHORIZED_USER:
                return "drawable://" + R.drawable.ic_authen_user;
            case NORMAL_USER:
                return "drawable://" + R.drawable.ic_authen_normal;
            case FAMOUS_TEAM:
                return "drawable://" + R.drawable.ic_authen_famous_team;
            case FAMOUS_EXPERT:
                return "drawable://" + R.drawable.ic_authen_famous_expert;
            default:
                return "";
        }
    }

//    /**
//     * 获取没有很长Url的文本
//     *
//     * @param
//     * @return
//     * @author yaohuix
//     * @date 2016/5/23 17:14
//     */
//    public static void getNoLongURLStr(TextView textView) {
//        int[][] index = new int[1000][2];//url的始末点
//        String[] urls = new String[1000];//url本身
//        String content = textView.getText().toString().trim();
//        int y = 0;
//        for (URLSpan urlSpan : textView.getUrls()) {
//            String url = urlSpan.getURL();
//            int i = content.indexOf(urlSpan.getURL());
//            while (i != -1) {
//                urls[y] = url;
//                index[y][0] = i;
//                content = content.substring(0, i) + "网页链接" + content.substring(i + url.length(), content.length());
//                index[y][1] = i + 4;
//                i = content.indexOf(url, index[y][1]);
//                y++;
//            }
//        }
//        SpannableString spannableString = new SpannableString(content);
//        for (int i = 0; i < y; i++) {
//            spannableString.setSpan(new URLSpan(urls[i]), index[i][0], index[i][1], Spanned.SPAN_INCLUSIVE_INCLUSIVE);
//        }
//        textView.setText(spannableString);
//    }

    /**
     * 校验字符的个数，是否符合
     *
     * @param str    需要校验的字符串
     * @param length 符合规定的长度
     * @return
     * @author yaohuix
     * @date 2016/4/6 17:10
     */
    public static boolean checkStrLength(String str, int length) {
        if (length <= 0) length = 0;
        return !(StringUtil.isNotEmpty(str) && str.trim().length() > length);
    }

    /**
     * String 转 long
     *
     * @param value
     * @return
     */

    public static long string2Long(String value) {
        try {
            return Long.valueOf(value);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return -1;
    }

    /**
     * 图片质量压缩
     *
     * @param
     * @return
     * @author yaohuix
     * @date 2016/4/13 14:14
     */

    public static byte[] compressImage(Bitmap image) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 100;
        while (baos.toByteArray().length / 1024 > 150) {  //循环判断如果压缩后图片是否大于500kb,大于继续压缩
            baos.reset();//重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%，把压缩后的数据存放到baos中
            options -= 10;//每次都减少10
            if (options < 10)
                break;
        }
//        ByteArrayInputStream isBm = new ByteArrayInputStream();//把压缩后的数据baos存放到ByteArrayInputStream中
//        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//把ByteArrayInputStream数据生成图片
        return baos.toByteArray();
    }

    public static String getFileName(String url) {
        if (StringUtil.isBlank(url)) {
            return "";
        }
        String fileName = url.substring(url.lastIndexOf("/") + 1, url.length());
        Log.d(TAG, "url:" + url + "  fileName:" + fileName);
        return fileName;
    }

    public static String getFilePath(String url, EFileType type) {
        //获取文件路径
        String filePath = getFileFolder(XYJApplication.mAppContext, type) + File.separator
                + PublicUtil.getFileName(url);
//        if (FileUtils.isFileExists(filePath)) {
//            return filePath;
//        }
        Log.d(TAG, "url:" + url + "  filePath:" + filePath);
        return filePath;
    }

    private static String getFileFolder(Context context, EFileType type) {
        String dirPath = null;
        try {
            dirPath = FileUtils.getXYJDir(context) + AppConstants.FILE_SEPARATOR + type.getValue();
            FileUtils.mkdir(dirPath);
            return dirPath;
        } catch (XYJException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 分享版本
     *
     * @param callback 分享之后的回调，可以为null
     * @return
     * @author yaohuix
     * @date 2016/5/5 16:10
     */
    public static void showShareVersion(PlatformActionListener callback) {
//        ShareSDK.initSDK(mContext);
        OnekeyShare oks = new OnekeyShare();
        //关闭sso授权
        //oks.disableSSOWhenAuthorize();
        // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
        oks.setTitle("戏友记下载");
        // titleUrl是标题的网络链接，仅在人人网和QQ空间使用
        oks.setTitleUrl("http://app.zheliyouxi.com/xiyouji/share/appshare.html");
        // text是分享文本，所有平台都需要这个字段
        oks.setText("中华文化，艺术精髓，这里百家争鸣。\n请你“逢场作戏”，欢迎加入戏友记。");
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
        oks.setImageUrl("http://7xr5o9.com2.z0.glb.qiniucdn.com/icon.png");//确保SDcard下面存在此张图片
        // url仅在微信（包括好友和朋友圈）中使用
        oks.setUrl("http://app.zheliyouxi.com/xiyouji/share/appshare.html");
        //comment是我对这条分享的评论，仅在人人网和QQ空间使用
        //oks.setComment("我是测试评论文本");
        // site是分享此内容的网站名称，仅在QQ空间使用
        oks.setSite("戏友记");
        // siteUrl是分享此内容的网站地址，仅在QQ空间使用
        oks.setSiteUrl("http://app.zheliyouxi.com/xiyouji/share/appshare.html");
        // 启动分享GUI
        oks.show(XYJApplication.mAppContext);
        if (callback != null)
            oks.setCallback(callback);
    }


    /**
     * 分享
     *
     * @param callback 分享之后的回调，可以为null
     * @return
     * @author yaohuix
     * @date 2016/5/5 16:10
     */
    public static void showShareContent(String title, String content, String url, PlatformActionListener callback) {
//        ShareSDK.initSDK(mContext);
        OnekeyShare oks = new OnekeyShare();
        //关闭sso授权
        //oks.disableSSOWhenAuthorize();
        // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
        oks.setTitle(title);
        // titleUrl是标题的网络链接，仅在人人网和QQ空间使用
        oks.setTitleUrl(url);
        // text是分享文本，所有平台都需要这个字段
        oks.setText(content);
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
        oks.setImageUrl("http://7xr5o9.com2.z0.glb.qiniucdn.com/icon.png");//确保SDcard下面存在此张图片
        // url仅在微信（包括好友和朋友圈）中使用
        oks.setUrl(url);
        //comment是我对这条分享的评论，仅在人人网和QQ空间使用
        //oks.setComment("我是测试评论文本");
        // site是分享此内容的网站名称，仅在QQ空间使用
        oks.setSite("戏友记");
        // siteUrl是分享此内容的网站地址，仅在QQ空间使用
        oks.setSiteUrl(url);
        // 启动分享GUI
        oks.show(XYJApplication.mAppContext);
        if (callback != null)
            oks.setCallback(callback);
    }

    /**
     * 文本中是否包含了圈子邀请
     *
     * @param
     * @return String[]     [0]：内容；[1]：群ID
     * @author yaohuix
     * @date 2016/5/11 9:57
     */
    public static String[] getGroupInvite(String str) {
        int start = str.indexOf("&$$&");//17
        int end = str.indexOf("$&&$");//26
        if (start != -1 && end != -1) {
            return new String[]{str.substring(0, start), str.substring(start + 4, end)};
        } else {
            return null;
        }
    }


    /**
     * 获取剧团认证对话框
     *
     * @param context
     * @param groupName   剧团名称
     * @param groupLeader 团长
     * @param catStr      剧种
     * @return
     */
    public static Dialog getAuthenDramaGroupDialog(Context context, String groupName, String groupLeader, String catStr) {
        Dialog dialog = new Dialog(context, R.style.MyDialogTheme);
        dialog.setCanceledOnTouchOutside(true);
        dialog.setCancelable(true);
        View view = LayoutInflater.from(context).inflate(R.layout.layout_famous_group_auth_dialog, null);
        ((MyTextView) view.findViewById(R.id.mtv_group_name)).setText(groupName);
        ((MyTextView) view.findViewById(R.id.mtv_group_leader_name)).setText(groupLeader);
        ((MyTextView) view.findViewById(R.id.mtv_group_cls)).setText(catStr);
        dialog.setContentView(view);
        return dialog;
    }

    /**
     * 获取演员认证对话框
     *
     * @param context
     * @param name           姓名
     * @param catStr         剧种
     * @param teacherFrom    师承
     * @param dramaGroupName 所属院团
     * @return
     */
    public static Dialog getAuthenActorDialog(Context context, String name, String teacherFrom, String catStr, String dramaGroupName) {
        Dialog dialog = new Dialog(context, R.style.MyDialogTheme);
        dialog.setCanceledOnTouchOutside(true);
        dialog.setCancelable(true);
        View view = LayoutInflater.from(context).inflate(R.layout.layout_famous_expert_auth_dialog, null);
        ((MyTextView) view.findViewById(R.id.mtv_name)).setText(name);
        ((MyTextView) view.findViewById(R.id.mtv_teacher)).setText(teacherFrom);
        ((MyTextView) view.findViewById(R.id.mtv_group_cls)).setText(catStr);
        ((MyTextView) view.findViewById(R.id.mtv_belong_org)).setText(dramaGroupName);
        dialog.setContentView(view);
        return dialog;
    }


    /**
     * 获取名家认证对话框
     *
     * @param context
     * @param name        姓名
     * @param teacherFrom 师承
     * @param catStr      剧种
     * @return
     */
    public static Dialog getAuthenExpertDialog(Context context, String name, String teacherFrom, String catStr) {
        Dialog dialog = new Dialog(context, R.style.MyDialogTheme);
        dialog.setCanceledOnTouchOutside(true);
        dialog.setCancelable(true);
        View view = LayoutInflater.from(context).inflate(R.layout.layout_famous_expert_auth_dialog, null);
        ((MyTextView) view.findViewById(R.id.mtv_name)).setText(name);
        ((MyTextView) view.findViewById(R.id.mtv_teacher)).setText(teacherFrom);
        ((MyTextView) view.findViewById(R.id.mtv_group_cls)).setText(catStr);
        view.findViewById(R.id.rl_belong_org).setVisibility(View.GONE);
        dialog.setContentView(view);
        return dialog;
    }

    public static int getCurrentAppVersion(Context context) {
        try {
            return context.getPackageManager().getPackageInfo(context.getPackageName(),
                    0).versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            return -1;
        }
    }

    /**
     * 获取渠道号
     * @return
     */
    public static String getChannelMeta(Context context) {
        String channel = "";
        try {
            ApplicationInfo appInfo = context.getPackageManager()
                    .getApplicationInfo(context.getPackageName(),
                            PackageManager.GET_META_DATA);
            channel = appInfo.metaData.getString("UMENG_CHANNEL");
        } catch (Exception e) {

        }finally {
            return channel;
        }
    }
}
